package com.power.thread.volatila;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description:
 * @author: jiangnan
 * @time: 2021/5/31 2:01 下午
 */
public class VolatileDemo {
    private volatile int num = 0;
    Lock lock = new ReentrantLock();
    private AtomicInteger atomicInteger = new AtomicInteger();

    //数据不一致的方案
    public void inc() {
        num++;
    }

    public void inc4() {
        atomicInteger.getAndIncrement();
    }

    //使用synchronized的方式解决
    public synchronized void inc2() {
        num++;
    }



    //采用锁的方式解决
    public void inc3() {
        lock.lock();
        try {
            num++;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }


    public static void main(String[] args) {
        VolatileDemo volatileDemo = new VolatileDemo();
        for (int i = 0; i < 10; i++) {
            new Thread() {
                @Override
                public void run() {
                    for (int j = 0; j < 1000; j++) {
//                        volatileDemo.inc();
//                        volatileDemo.inc2();
//                        volatileDemo.inc3();

                    }
                }
            }.start();
        }
        while (Thread.activeCount() > 1)
            Thread.yield();
        System.out.println(volatileDemo.num);
    }
}
